<template>
  <div class="table">
    <div class="user-header">
      <el-button type="primary" @click="addUser">新增</el-button>
      <el-form :inline="true" :model="formData">
        <el-form-item label="请输入 : ">
          <el-input
            type="text"
            placeholder="请输入搜索内容"
            v-model="formData.keyWrods"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        v-for="item in tableLable"
        :prop="item.prop"
        :key="item.prop"
        :label="item.label"
        :width="item.width"
        :min-width="item.minWidth"
      />

      <el-table-column fixed="right" label="Operations" min-width="120">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDel(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pager">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="config.count"
        @current-change="handleChange"
      />
    </div>

    <!----新增--->
    <el-dialog
      v-model="dialogVisible"
      :title="action == 'add' ? '新增用户' : '编辑用户'"
      width="500"
      :before-close="handleClose"
    >
      <el-form :model="form" label-width="auto" :rules="rules" ref="userForm">
        <el-form-item label="姓名 : " prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="年龄 : " prop="age">
          <el-input v-model="form.age" />
        </el-form-item>
        <el-form-item label="性别 : " prop="sex">
          <el-select v-model="form.sex">
            <el-option label="男" value="1" />
            <el-option label="女" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期 :" prop="birth">
          <el-date-picker
            v-model="form.birth"
            type="date"
            placeholder="Pick a date"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="地址 :" prop="addr">
          <el-input v-model="form.addr" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive, nextTick } from "vue";
import { getUserData, deleteUser, createUser, updateUser } from "@/api/user.js";
import { ElMessage, ElMessageBox } from "element-plus";
const handleClick = () => {
  console.log("click");
};

let tableData = ref([]);
let formData = reactive({
  keyWrods: "",
});
const tableLable = reactive([
  {
    prop: "name",
    label: "姓名",
    minWidth: 200,
  },
  {
    prop: "age",
    label: "年龄",
    width: 100,
  },
  {
    prop: "sexLabel",
    label: "性别",
    width: 200,
  },
  {
    prop: "birth",
    label: "出生日期",
    width: 200,
  },
  {
    prop: "addr",
    label: "地址",
    minWidth: 200,
  },
]);
const config = reactive({
  count: 0,
  name: "",
});

let dialogVisible = ref(false);
let action = ref("add");
let form = reactive({
  sex: "1",
});
let rules = reactive({
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  age: [
    { required: true, message: "请输入年龄", trigger: "blur" },
    // {
    //   type: "number",
    //   message: "年龄必须是数字",
    //   trigger: "blur",
    // },
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  birth: [{ required: true, message: "请选择出生日期", trigger: "change" }],
  addr: [{ required: true, message: "请输入地址", trigger: "blur" }],
});
const userForm = ref(null);

const getData = async (search) => {
  const data = await getUserData(search);
  tableData.value = data.list.map((o) => ({
    ...o,
    sexLabel: o.sex === 1 ? "男" : "女",
  }));
  config.count = data.count;
  console.log(tableData);
};
const handleSearch = () => {
  config.name = formData.keyWrods;
  config.page = 1;
  getData(config);
};

const handleChange = (page) => {
  config.page = page;
  getData(config);
};

// 删除
const handleDel = (val) => {
  ElMessageBox.confirm("是否确认删除该用户").then(async () => {
    await deleteUser({ id: val.id });
    ElMessage.success("删除成功");
    getData();
  });
};

const handleClose = () => {
  dialogVisible.value = false;
};

const addUser = () => {
  action.value = "add";
  dialogVisible.value = true;
};

const submit = () => {
  let tip = action == "add" ? "添加成功" : "更新成功";
  userForm.value.validate(async (valid) => {
    if (valid) {
      console.log(form);
      let res = null;
      if (action.value === "add") {
        res = await createUser(form);
      } else {
        res = await updateUser(form);
      }
      if (res) {
        ElMessage.success(tip);
        getData();
        dialogVisible.value = false;
        userForm.value.resetFields();
      }
    }
  });
};
const handleEdit = (row) => {
  action.value = "edit";
  dialogVisible.value = true;
  // ''+row.sex 是将sex转为字符串
  // 避免在页面没有渲染完后就赋值
  nextTick(() => {
    Object.assign(form, { ...row, sex: "" + row.sex });
  });
};
onMounted(() => {
  getData();
});
</script>
<style lang="less" scoped>
.table {
  width: 100%;
  height: 100%;
}
.user-header {
  display: flex;
  justify-content: space-between;
}
.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
